package com.cms.server.resolver.plugins;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.efounder.builder.base.data.DataSetUtils;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JParamObject;
import com.efounder.form.EFFormDataModel;
import com.efounder.form.io.FormDataResolverAdapter;
import com.efounder.form.server.resolver.util.SYS_MDL_VAL;
import com.efounder.sql.JStatement;
import com.metadata.bizmodel.SYS_MODEL;
import com.persistence.FLOW_TASK_LIST;

public class CMSSubmitPSHTFormToFlow extends FormDataResolverAdapter {

	//初始化FormDataModel
	public void finishSaveForm(JStatement stmt, EFFormDataModel model, JParamObject PO) throws Exception {
		EFDataSet                    billDataSet = model.getBillDataSet();
		EFDataSet                      BMDataset = EFDataSet.getInstance(new String[]{"F_BMBH"});
		EFDataSet                    flowDataSet = EFDataSet.getInstance("FLOW_TASK_LIST");
		EFDataSet                  bmFlowDataSet = EFDataSet.getInstance("FLOW_TASK_LIST");
		EFRowSet                        BMRowSet = null;
		EFRowSet                      itemRowSet;
		EFRowSet                      flowRowSet;
		EFRowSet                    bmFlowRowSet;
		EFDataSet                    itemDataSet;
		String                            strSql = "";
		ResultSet                             rs = null;
		ResultSet                bmFlowResultSet = null;
		long                             curTime = new Date().getTime();
		String                            F_KJQJ = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BLFL_KJQJ_COL_, SYS_MDL_VAL.BILL_KJQJ), "");
		String                            F_GUID = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_GUID_COL_, SYS_MDL_VAL.BILL_GUID), "");
		String                            F_DJBH = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_BH_COL_, SYS_MDL_VAL.BILL_BH), null);
		String                           FLOW_ID = "";
		String                         NODE_NAME = "";
		String                     RESR_IN_CAUSE = PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "");
		java.util.List<String>    dataSetKeyList = new java.util.ArrayList<String>();
		Map<String, EFRowSet>            itemBMMap = new HashMap<String, EFRowSet>();
		
		//部门建立索引
		if(billDataSet.getRowCount() > 0) {
			itemRowSet = billDataSet.getRowSet(0);
			dataSetKeyList = itemRowSet.getDataSetKeyList();
			if(dataSetKeyList.size() > 0) {
				itemDataSet = itemRowSet.getDataSet(dataSetKeyList.get(0));
				for(int i = 0; i < itemDataSet.getRowCount(); i++){
					itemBMMap.put(itemDataSet.getRowSet(i).getString("F_BMBH", ""), itemDataSet.getRowSet(i));
				}
			}
		}
		
		strSql = " select * from FLOW_TASK_LIST where BIZ_DATE = '" + F_KJQJ + "' and BIZ_DJBH = '" + F_DJBH + "' and "
			   + " FLOW_ID = 'PSHT_EDIT_FLOW' and NODE_TAG = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "'"
			   + " order by (OP_ID + 0) desc";
		rs = stmt.executeQuery(strSql);
		flowDataSet = DataSetUtils.resultSet2DataSet(rs, flowDataSet);

		//开始节点单独处理，保存后就要进入流程任务列表，只要保存一次，以后就不再更新
		if(flowDataSet == null || flowDataSet.getRowCount() == 0) {
			strSql = "select * from FLOW_TASK_LIST where FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "' and BIZ_DATE = '" + F_KJQJ + "' and "
		           + " BIZ_GUID = '" + F_GUID + "' and BIZ_DJBH ='" + F_DJBH + "' and OP_NODE = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "' and "
		           + " OP_NODE = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "' and NODE_TAG = ''";
			rs = stmt.executeQuery(strSql);
			if(rs != null && rs.next()) return;
			strSql = "insert into FLOW_TASK_LIST (OP_ID,FLOW_ID,BIZ_DJBH,BIZ_DATE,BIZ_GUID,OP_USER,OP_USER_NAME,OP_TIME,NODE_TAG,NODE_TAG_NAME,"
				   + "OP_BMBH,OP_NOTE,TASK_STATUS,OP_NODE,NODE_SRC,NODE_SRC_NAME,POP_ID,RESR_STATUS,RESR_IN_CAUSE," ;
			for(int j = 1; j <= 20; j++) {
		    	if(j < 10) {
		    		strSql += "F_CHAR0" + j + ",";
		    	} else {
		    		strSql += "F_CHAR" + j + ",";
		    	}
		    }
			strSql += "RESR_OUT_CAUSE) values ('" + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "', '"
				   + F_DJBH + "', '" + F_KJQJ + "', '" + F_GUID + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER, "")
				   + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, "") + "', '"
				   + curTime + "','" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "','" + PO.GetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, "") 
				   + "','" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_BMBH, "") + "', '" + billDataSet.getRowSet(0).getString("F_BZ", "") + "', 'processing', '"
				   + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '"
				   + PO.GetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, "") + "', '', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "") 
				   + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "") + "',";
			for(int j = 1; j <= 20; j++) {
		    	if(j < 10) {
		    		strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, "")  + "',";
		    	} else {
		    		strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, "") + "',";
		    	}
		    }
			strSql += "'')";
			stmt.execute(strSql);
			return;
		}
		
		flowRowSet = flowDataSet.getRowSet(0);
		
		//如果提交原因是create，则是保存；如果为submit，则为提交
		//如果是create，则跳过
		if(PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "").equals("create")) return;
		
		//如果不是开始节点，则需要更新上一个流程节点任务信息，同时还要插入一条新的记录
		FLOW_ID = flowRowSet.getString("FLOW_ID", "");
		RESR_IN_CAUSE = flowRowSet.getString("RESR_IN_CAUSE", "");
			
		//获取提交到节点名称
		strSql = "select * from FLOW_NODE_LIST where FLOW_ID ='" + FLOW_ID + "' and NODE_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE_NEXT, "") + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) NODE_NAME = rs.getString("NODE_NAME");
			
		//查询部门
		strSql = " select F_BMBH, F_BMMC from HYBMZD where F_SYZT = '1'";
		rs = stmt.executeQuery(strSql);
		BMDataset = DataSetUtils.resultSet2DataSet(rs, BMDataset);

		//开始节点提交单据，有两种情况
		//1：制单提交，需要把所有部门都提交
		//2: 部分部门退回后提交，只需要把退回部门的分录提交，如果有新增的，则新加，如果删除分录的话，需要把任务状态更新
		if(RESR_IN_CAUSE.equals("create") || (flowRowSet.getString("NODE_SRC", "").equals("N1") && flowRowSet.getString("NODE_TAG", "").equals("N1"))) {
			//更新上一个任务节点的状态
			strSql = "update FLOW_TASK_LIST set RESR_STATUS = 'processed', RESR_OUT_CAUSE = '" 
				   + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "") + "' where OP_ID = '" 
				   + flowRowSet.getString("OP_ID", "") + "' and FLOW_ID = '" + FLOW_ID + "'";
			stmt.execute(strSql);
			//操作节点
			PO.SetValueByEnvName("NODE_OP_ID", flowRowSet.getString("OP_ID", ""));

			if(billDataSet.getRowCount() > 0) {
				itemRowSet = billDataSet.getRowSet(0);
				dataSetKeyList = itemRowSet.getDataSetKeyList();
				if(dataSetKeyList.size() > 0) {
					itemDataSet = itemRowSet.getDataSet(dataSetKeyList.get(0));
					curTime = new Date().getTime();
					for(int i = 0; i < itemDataSet.getRowCount(); i++){
				    	itemRowSet = itemDataSet.getRowSet(i);
				    	//如果多个部门同时提交，时间可能一样，所以为了防止插入引起主键重复，所以加1					    
					    BMRowSet = (EFRowSet) BMDataset.getRowSet(itemRowSet.getString("F_BMBH", ""));		
					    insertNewFlowRow(stmt, PO, F_DJBH, F_GUID, F_KJQJ, NODE_NAME, BMRowSet, flowRowSet, curTime);
					    curTime++;
					}
				}
			}
		}
		
		//把退回的部门分录提交任务,如果有新增的部门也同时提交
		else {
			strSql = " select * from FLOW_TASK_LIST where BIZ_DATE = '" + F_KJQJ + "' and BIZ_DJBH = '" + F_DJBH + "' and "
			       + " FLOW_ID = 'PSHT_EDIT_FLOW' and NODE_TAG = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "'"
			       + " and RESR_STATUS = 'pending' order by (OP_ID + 0) desc";
			bmFlowResultSet = stmt.executeQuery(strSql);
			bmFlowDataSet = DataSetUtils.resultSet2DataSet(bmFlowResultSet, bmFlowDataSet);
			for(int i = 0; i < bmFlowDataSet.getRowCount(); i++) {
				bmFlowRowSet = bmFlowDataSet.getRowSet(i);
			    curTime = new Date().getTime();
			    BMRowSet = (EFRowSet) BMDataset.getRowSet(bmFlowRowSet.getString("TASK_TO_UNIT", ""));	
			    //如果流程的代办任务在单据分录中不存在，说明退回后把该单位删除了
			    if(itemBMMap.get(bmFlowRowSet.getString("TASK_TO_UNIT", "")) == null) {
			    	strSql = "update FLOW_TASK_LIST set RESR_STATUS = 'processed', RESR_OUT_CAUSE = 'delete' where OP_ID = '" 
						   + bmFlowRowSet.getString("OP_ID", "") + "' and FLOW_ID = '" + FLOW_ID + "'";
					stmt.execute(strSql);
					itemBMMap.remove(bmFlowRowSet.getString("TASK_TO_UNIT", ""));
			    }
			    //如果修改部门信息，则插入一条部门的任务信息
			    strSql = "insert into FLOW_TASK_LIST (OP_ID,FLOW_ID,BIZ_DJBH,BIZ_DATE,BIZ_GUID,OP_USER,OP_USER_NAME,OP_TIME,"
					   + "OP_BMBH,OP_NOTE,TASK_STATUS,OP_NODE,NODE_SRC,NODE_SRC_NAME,NODE_TAG,NODE_TAG_NAME,POP_ID,RESR_STATUS," 
					   + "RESR_IN_CAUSE,RESR_OUT_CAUSE," ;
			    for(int j = 1; j <= 20; j++) {
			    	if(j < 10) {
			    		strSql += "F_CHAR0" + j + ",";
			    	} else {
			    		strSql += "F_CHAR" + j + ",";
			    	}
			    }
			    strSql += "TASK_TO_UNIT,TASK_TO_UNIT_NAME) values ('"
			            + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "', '"
					    + F_DJBH + "', '" + F_KJQJ + "', '" + F_GUID + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER, "")
					    + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, "") + "', '"
						    + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_BMBH, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NOTE, "") + "', 'processing', '"
						    + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '"
						    + PO.GetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE_NEXT, "") + "', '" + NODE_NAME 
						    + "', '" + bmFlowRowSet.getString("OP_ID", "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "") 
						    + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "") + "', '', ";
			    for(int j = 1; j <= 20; j++) {
			    	if(j < 10) {
			    		strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, "")  + "',";
			    	} else {
			    		strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, "") + "',";
			    	}
			    }
			    strSql += "'" + BMRowSet.getString("F_BMBH", "") + "', '" + BMRowSet.getString("F_BMMC", "") + "')";
				stmt.execute(strSql);
				
				//同时更新刚才节点的任务状态
				strSql = "update FLOW_TASK_LIST set RESR_STATUS = 'processed', RESR_OUT_CAUSE = '" 
					   + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "") + "' where OP_ID = '" 
					   + bmFlowRowSet.getString("OP_ID", "") + "' and FLOW_ID = '" + FLOW_ID + "'";
				stmt.execute(strSql);
				itemBMMap.remove(bmFlowRowSet.getString("TASK_TO_UNIT", ""));
			}
			
			//如果单据分录中还有记录，说明是新添加的
			Iterator it = itemBMMap.entrySet().iterator();
			curTime = new Date().getTime();
			while(it.hasNext()) {
				Map.Entry m = (Entry) it.next();
				//如果多个部门同时提交，时间可能一样，所以为了防止插入引起主键重复，所以加1
			    curTime = new Date().getTime() + 1;
			    itemRowSet = itemBMMap.get(m.getKey().toString());
			    if(itemRowSet.getString("F_FLZT", "1").equals("1")) continue;
			    //如果有已经提交流程的，就跳过
			    strSql = " select * from FLOW_TASK_LIST where BIZ_DATE = '" + F_KJQJ + "' and BIZ_DJBH = '" + F_DJBH + "' and "
			           + " FLOW_ID = 'PSHT_EDIT_FLOW' and NODE_TAG = 'N2' and NODE_SRC = 'N1' "
			           + " and RESR_STATUS = 'pending' order by (OP_ID + 0) desc";
			    rs = stmt.executeQuery(strSql);
			    if(rs != null && rs.next()) continue;
			    
			    BMRowSet = (EFRowSet) BMDataset.getRowSet(m.getKey().toString());		
			    insertNewFlowRow(stmt, PO, F_DJBH, F_GUID, F_KJQJ, NODE_NAME, BMRowSet, flowRowSet, curTime);
			    curTime++;
			}
		}
	}
	
	private void insertNewFlowRow(JStatement stmt, JParamObject PO, String F_DJBH, String F_GUID, 
			                      String F_KJQJ, String NODE_NAME, EFRowSet BMRowSet, 
			                      EFRowSet flowRowSet, long curTime) throws SQLException {
		String                            strSql = "";
		
		//每一个部门一条任务信息
	    strSql = "insert into FLOW_TASK_LIST (OP_ID,FLOW_ID,BIZ_DJBH,BIZ_DATE,BIZ_GUID,OP_USER,OP_USER_NAME,OP_TIME,"
			   + "OP_BMBH,OP_NOTE,TASK_STATUS,OP_NODE,NODE_SRC,NODE_SRC_NAME,NODE_TAG,NODE_TAG_NAME,POP_ID,RESR_STATUS," 
			   + "RESR_IN_CAUSE,RESR_OUT_CAUSE," ;
	    for(int j = 1; j <= 20; j++) {
	    	if(j < 10) {
	    		strSql += "F_CHAR0" + j + ",";
	    	} else {
	    		strSql += "F_CHAR" + j + ",";
	    	}
	    }
	    strSql += "TASK_TO_UNIT,TASK_TO_UNIT_NAME) values ('"
	            + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "', '"
			    + F_DJBH + "', '" + F_KJQJ + "', '" + F_GUID + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER, "")
			    + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, "") + "', '"
				+ curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_BMBH, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NOTE, "") + "', 'processing', '"
				+ PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '"
				+ PO.GetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE_NEXT, "") + "', '" + NODE_NAME 
				+ "', '" + flowRowSet.getString("OP_ID", "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "") 
			    + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "") + "', '',";
	    for(int j = 1; j <= 20; j++) {
	    	if(j < 10) {
	    		strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, "")  + "',";
	    	} else {
	    		strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, "") + "',";
	    	}
	    }
	    strSql += "'" + BMRowSet.getString("F_BMBH", "") + "', '" + BMRowSet.getString("F_BMMC", "") + "')";
		stmt.execute(strSql);
	}
}
